package com.serkol.ams.controller.api;

import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.serkol.ams.bean.GoodsParam;
import com.serkol.ams.bean.MyPage;
import com.serkol.ams.bean.MyPageOld;
import com.serkol.ams.bean.Result;
import com.serkol.ams.entity.*;
import com.serkol.ams.modal.SqlFeildModal;
import com.serkol.ams.service.AgentService;
import com.serkol.ams.service.CloudInventoryService;
import com.serkol.ams.service.GoodAgentPriceService;
import com.serkol.ams.service.GoodsService;
import com.serkol.annotation.IsLogin;
import com.serkol.annotation.RedisCache;
import com.serkol.annotation.RedisCacheRemove;
import com.serkol.config.RedisUtil;
import com.serkol.constant.AuthConstant;
import com.serkol.constant.ResultConstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("api/goods")
@CacheConfig(cacheNames = "user")
public class GoodsApiController {
    @Autowired
    private GoodsService goodsService;

    @Autowired
    private GoodAgentPriceService goodAgentPriceService;

    @Autowired
    private AgentService agentService;


    @Autowired
    private CloudInventoryService cloudInventoryService;
    @Autowired
    private RedisUtil redisUtil;

    @Value("${upload.host}")
    private String uploadhost;

    @GetMapping("/findByList")
    public Result findByList() {
        List<Goods> list = goodsService.list();
        return Result.ok(list);
    }

    @IsLogin
    @GetMapping("/findByPageList")
    public Result findByPageList(@RequestParam(name = "pageSize", defaultValue = "10") int pageSize, @RequestParam(name = "current", defaultValue = "0") int current) {
        AuthConstant.setPathUrl(uploadhost);
        Result result = new Result();
        return goodsService.findByList(pageSize, current);

    }

    @IsLogin
    @GetMapping("/findByPageIntegralList")
    public Result findByPageIntegralList(@RequestParam(name = "pageSize", defaultValue = "10") int pageSize, @RequestParam(name = "current", defaultValue = "0") int current) {
        AuthConstant.setPathUrl(uploadhost);
        Result result = new Result();
        return goodsService.findByPageIntegralList(pageSize, current);

    }

    @IsLogin
    @GetMapping("/findByCloudPageList")
    public Result findByCloudPageList(@RequestParam(name = "pageSize", defaultValue = "10") int pageSize, @RequestParam(name = "current", defaultValue = "0") int current) {
        AuthConstant.setPathUrl(uploadhost);
        Result result = new Result();
        return goodsService.findByCloudPageList(pageSize, current);

    }

    @IsLogin
    @GetMapping("/findByNewList")
    //W   @RedisCache(key = "goods::home::findByNewList",isLang = true,isParam = true)
    public Result findByNewList(@RequestParam(value = "agentId", defaultValue = "0") long agentId,
                                @RequestParam(value = "categoryId", defaultValue = "0") long categoryId) {
        AuthConstant.setPathUrl(uploadhost);
        LoginLog loginLog = AuthConstant.getLoginLog();
        boolean flag = false;
        if(agentId > 0){
            flag = true;
            loginLog.setAgentId(agentId);
        }
        //    System.out.println("categoryId:"+categoryId);

        QueryWrapper<Goods> queryWrapper = new QueryWrapper<>();
        if(flag){
            queryWrapper.select(SqlFeildModal.getGoodsNewListFeild((loginLog.getAgentId() != null) ? loginLog.getAgentId() : 0));
        }else {
            queryWrapper.select(SqlFeildModal.getGoodsNewListShopFeild((loginLog.getAgentId() != null) ? loginLog.getAgentId() : 0));
        }

        if (categoryId > 0) {
            queryWrapper.lambda().eq(Goods::getCategoryId, categoryId);
        }
        List<Map<String, Object>> list = goodsService.listMaps(queryWrapper);
        return Result.ok(list);
    }

    @IsLogin
    @GetMapping("/findByShopList")
    //W   @RedisCache(key = "goods::home::findByNewList",isLang = true,isParam = true)
    public Result findByShopList(
                                @RequestParam(value = "categoryId", defaultValue = "0") long categoryId) {
        AuthConstant.setPathUrl(uploadhost);
        LoginLog loginLog = AuthConstant.getLoginLog();

        //    System.out.println("categoryId:"+categoryId);

        QueryWrapper<Goods> queryWrapper = new QueryWrapper<>();

            queryWrapper.select(SqlFeildModal.getGoodsNewListShopFeild((loginLog.getAgentId() != null) ? loginLog.getAgentId() : 0));


        if (categoryId > 0) {
            queryWrapper.lambda().eq(Goods::getCategoryId, categoryId);
        }
        List<Map<String, Object>> list = goodsService.listMaps(queryWrapper);
        return Result.ok(list);
    }

    @GetMapping("/findByHomeist")
    //  @Cacheable(cacheNames = "goods::home", key = "'findByHomeist'")
    @RedisCache(key = "goods::home::findByHomeist", isLang = true, isAuth = true, isAgent = true)
    public Result findByHomeist() {
        AuthConstant.setPathUrl(uploadhost);
        //    System.out.println("categoryId:"+categoryId);
        LoginLog loginLog = AuthConstant.getLoginLog();
        System.out.println("Login");
        System.out.println(loginLog);
        QueryWrapper<Goods> queryWrapper = new QueryWrapper<>();
        if (loginLog.getAgentId() != null) {
            queryWrapper.select(SqlFeildModal.getGoodsHomeListFeild(loginLog.getAgentId()));
        } else {
            queryWrapper.select(SqlFeildModal.getGoodsHomeListFeild(0));
        }

        List<Map<String, Object>> list = goodsService.listMaps(queryWrapper);
        return Result.ok(list);
    }


    //findById
    //   @RedisCache(key = "goods::one::findById",isLang = true,isParam = true,isAgent = true)
    @GetMapping("/findById")
    public Result findById(@RequestParam(value = "id", defaultValue = "0") long id) {
        AuthConstant.setPathUrl(uploadhost);
        //    System.out.println("categoryId:"+categoryId);
        LoginLog loginLog = AuthConstant.getLoginLog();
        QueryWrapper<Goods> queryWrapper = new QueryWrapper<>();
        queryWrapper.select(SqlFeildModal.getGoodsFeild((loginLog.getAgentId() != null) ? loginLog.getAgentId() : 0));
        queryWrapper.lambda().eq(Goods::getId, id);
        Map<String, Object> map = goodsService.getMap(queryWrapper);

        return Result.ok(map);
    }

    @IsLogin
    @GetMapping("/findByBackId")
    public Result findByBackId(@RequestParam(value = "id", defaultValue = "0") long id) {

        Goods byId = goodsService.getById(id);

        return Result.ok(byId);
    }

    @IsLogin
    @GetMapping("/findByBackShowId")
    public Result findByBackShowId(@RequestParam(value = "id", defaultValue = "0") long id) {
        AuthConstant.setPathUrl(uploadhost);
        //    System.out.println("categoryId:"+categoryId);
        LoginLog loginLog = AuthConstant.getLoginLog();
        QueryWrapper<Goods> queryWrapper = new QueryWrapper<>();
        queryWrapper.select(SqlFeildModal.getGoodsBackFeild((loginLog.getAgentId() != null) ? loginLog.getAgentId() : 0));
        queryWrapper.lambda().eq(Goods::getId, id);
        Map<String, Object> map = goodsService.getMap(queryWrapper);

        return Result.ok(map);
    }

    @IsLogin
    @GetMapping("/findByGoodsAngent")
    // @Cacheable(cacheNames = "goods::home::agent", key = "'findByGoodsAngent'+#id")
    @RedisCache(key = "goods::home::findByGoodsAngent", isLang = true, isParam = true)
    public Result findByGoodsAngent(@RequestParam(value = "id", defaultValue = "0") long id) {
        //    System.out.println("categoryId:"+categoryId);
        LoginLog loginLog = AuthConstant.getLoginLog();
        QueryWrapper<Agent> queryWrapper = new QueryWrapper<>();
        queryWrapper.select(SqlFeildModal.getGoodsAgentPriceFeild(id));
        List<Map<String, Object>> maps = agentService.listMaps(queryWrapper);
        return Result.ok(maps);
    }

    @IsLogin
   // @RedisCacheRemove(key = "goods::home::findByGoodsAngent")
    @RequestMapping("edit")
    public Result edit(@RequestBody GoodsParam goods) {
        //  GoodsParam goods = object.toJavaObject(GoodsParam.class);
        System.out.println(goods);
        boolean b = false;
        if (goods.getId() != null) {
            b = goodsService.updateById(goods);
        } else {
            b = goodsService.save(goods);
        }
        if (b) {
            List<GoodAgentPrice> agents = goods.getAgents();
            List<GoodAgentPrice> agents1 = new ArrayList<>();
            Iterator<GoodAgentPrice> iterator = agents.iterator();

            while (iterator.hasNext()) {
                GoodAgentPrice next = iterator.next();
                next.setGoodId(goods.getId());
                System.out.println(next);
                agents1.add(next);
            }
            goodAgentPriceService.saveOrUpdateBatch(agents1);
            redisUtil.del("goods::home::agent");

        }
        return b ? Result.ok() : Result.failure(ResultConstant.FAIL);
    }

    @IsLogin
    @GetMapping("/findByBackSelectList")
    public Result findByBackSelectList() {
        QueryWrapper<Goods> query = new QueryWrapper<>();
        query.select(SqlFeildModal.getGoodsSelectFeild());
        List<Map<String, Object>> list = goodsService.listMaps(query);
        return Result.ok(list);
    }

    @IsLogin
    @PostMapping("cloudChange")
    public Result cloudChange(@RequestBody JSONObject jsonObject) {
        long goodsId = jsonObject.getLongValue("goodsId");
        int type = jsonObject.getIntValue("type");

        System.out.println("goodsId:" + goodsId + " Type:" + type);
        Goods goods = new Goods();
        goods.setId(goodsId);
        goods.setCloudType(type);
        boolean b = goodsService.updateById(goods);
        if (b) {
            return Result.ok();
        } else {
            return Result.failure();
        }

    }


    @GetMapping("/findByMyCloudList")
    //@RedisCache(key = "goods::home::findByMyCloudList",isLang = true,isParam = true,isAgent = true)
    public Result findByMyCloudList() {
        AuthConstant.setPathUrl(uploadhost);

        List<Map<String, Object>> list = cloudInventoryService.findByMyCloudList();
        return Result.ok(list);
    }

    @GetMapping("/findByMyCloudPageList")
    //@RedisCache(key = "goods::home::findByMyCloudList",isLang = true,isParam = true,isAgent = true)
    public Result findByMyCloudPageList(@RequestParam(name = "pageSize", defaultValue = "10") int pageSize, @RequestParam(name = "current", defaultValue = "0") int current
            , @RequestParam(name = "userId", defaultValue = "0") long userId) {
        AuthConstant.setPathUrl(uploadhost);

        return cloudInventoryService.findByMyCloudPageList(pageSize, current, userId);
    }
    @IsLogin
    @PostMapping("addCloudOrder")
   public Result addCloudOrder(@RequestBody CloudInventory inventory){
        boolean b = cloudInventoryService.addOrder(inventory);
        return b? Result.ok() : Result.failure();
    }
}
